package com.elong.android.specialhouse.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.dp.android.elong.crash.LogWriter;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.adapter.ApartmentSeachHistroyAdapter;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.entity.ApartmentCitysSuggestList;
import com.elong.android.specialhouse.entity.ApartmentKeyword;
import com.elong.android.specialhouse.entity.ApartmentSearchChildDataInfo;
import com.elong.android.specialhouse.entity.ApartmentSearchDataInfo;
import com.elong.android.specialhouse.entity.ApartmentSearchParam;
import com.elong.android.specialhouse.entity.ApartmentSelectSerchChildInfo;
import com.elong.android.specialhouse.entity.ApartmentSuggestListEntity;
import com.elong.android.specialhouse.request.GetLocationListReq;
import com.elong.android.specialhouse.request.HouseSuggestReq;
import com.elong.android.specialhouse.ui.ApartmentAreaView;
import com.elong.android.specialhouse.utils.ApartmentAreaUtils;
import com.elong.android.specialhouse.utils.CacheHelper;
import com.elong.android.specialhouse.utils.JSONHelper;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author yang.yu
 * @ClassName: ApartmentAreaSelectActivity
 * @Description: 区域位置选择
 * @date 2015-8-31 上午10:30:03
 */
public class ApartmentAreaSelectActivity extends BaseVolleyActivity<IResponse<?>> implements TextWatcher, OnItemClickListener,
OnEditorActionListener{


	private String cityName = null;
	private String cityId = null;
	private boolean isItemSelected = false;
	
	/**
	 * 搜索匹配Liewview
	 */
	private ListView m_searchResultList;
	
	/**
	 * 匹配结果 PopupWindow
	 */
	private PopupWindow m_searchResultWindow;
	
	/**
	 * 清除编辑框按钮
	 */
	private View m_clearButton;
	
	/**
	 * 关键词编辑框
	 */
	private EditText m_searchEditText;
	private final static int DROPDOWN_OFFX = 0;
	private final static int DROPDOWN_OFFY = -2;
	private boolean isFadeOut = false;
	private ApartmentKeyword apartmentKeyword;

	/**
	 * 搜索匹配搜索历史ListView
	 */
	private ListView seachHistroyListView;	
	private ApartmentSeachHistroyAdapter histroyAdapter;
	private ArrayList<HashMap<String, Object>> histroyData;
	
	/**
	 *  搜索记录保存的最大数目,3条
	 */
	private final static int HISTROY_MAXNUM = 3; 
	
	/**
	 *  SP中存储名
	 */
	private final static String SP_APARTMENTSEARCHHISTROTY = "ApartmentSearchHistroty";
	
	/**
	 * 进入此页面时是否默认显示状态，true为默认显示edit状态，且不可显示AreaBrandView，false默认显示AreaBrandView
	 */
	private boolean dismisskeywordsv = false;

	private Animation animationDownin;

	/**
	 * 定位超时Message
	 */
	public final static int MESSAGE_LOCATE_TIMEOUT = 0;
	
	/**
	 * 获取关键词Message
	 */
	public final static int MESSAGE_GET_SUGGESTION = 1;
	
	/**
	 *  用户输入关键词的时间间隔:2s(超过该时间间隔则向后台获取suggestion)
	 */
	public final static int KEYWORD_INPUT_INTERVAL = 500;

	private Handler m_handler;

	private String keywordtypestr;
	
	/**
	 *  选中的
	 */
	private ApartmentSelectSerchChildInfo mSSInfo;
	
	/**
	 * 区域品牌视图
	 */
	private ApartmentAreaView apartmentAreaView;
	
	
	/**
	 * 取消按钮，显示AreaBrandView
	 */
	private TextView m_cancelButton;
	

	private ApartmentSearchParam mSearchParam;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Intent intent = getIntent();
		cityName = intent.getStringExtra(AppConstants.BUNDLEKEY_CITYNAME);
		cityId = intent.getStringExtra(AppConstants.BUNDLEKEY_CITYID);
		mSSInfo = (ApartmentSelectSerchChildInfo) intent
				.getSerializableExtra("selectedNode");
		if (Utils.isEmptyString(cityId)) {
			cityId = Utils.retriveCityIdByCityName(this, cityName);
		}
//		if (Utils.isEmptyString(cityName) || Utils.isEmptyString(cityId)) {
//			mSearchParam = (ApartmentSearchParam) intent.getSerializableExtra("ApartmentSearchParam");
//			if (mSearchParam != null) {
//				cityName = mSearchParam.CityName;
//				cityId = mSearchParam.CityID;
//			}
//		}
//		apartmentKeyword = (ApartmentKeyword) intent.getSerializableExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT);
		apartmentKeyword = new ApartmentKeyword();
		// 初始化消息处理器
		initMessageHandler();
		
		
		// 初始化历史记录的listview
		initHistoryListView();
		apartmentAreaView.setOnSelectLeafListener(new ApartmentAreaView.OnApartmentAreaViewListener() {

			@Override
			public void exeSelectLeaf(ApartmentSearchChildDataInfo data) {
				Intent intent = new Intent();
				ApartmentKeyword keyword = ApartmentAreaUtils.changeToApartmentKeyword(data);
				intent.putExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT, keyword);
				setResult(Activity.RESULT_OK, intent);
				finish();
			}

			@Override
			public void exeNoAreaData() {
			}
		});
		
		//请求公寓的所有数据
		initApartmentBrandAdapter();
		
//		if (StringUtils.isEmpty(apartmentKeyword.getName())) {
		// showHistroyOrSelector();
		// }

		initKeywordEditText();
	}

	protected void initContentView() {
		setContentView(R.layout.act_apartment_area_select);
		apartmentAreaView = (ApartmentAreaView) findViewById(R.id.treeView);
	}

	
	/**
	 * 
	 * @Title: initMessageHandler 
	 * @Description: TODO(初始化消息处理handler) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void initMessageHandler() {
		m_handler = new Handler(new Callback() {

			@Override
			public boolean handleMessage(Message msg) {
				switch (msg.what) {
				case MESSAGE_GET_SUGGESTION:
					String keyword = (String) msg.obj;
					getSuggestByKeyWord(keyword);
					break;
				}
				return false;
			}
		});
	}

	/**
	 * 
	 * @Title: initApartmentBrandAdapter 
	 * @Description: TODO(请求公寓的所有数据) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	protected void initApartmentBrandAdapter() {
		String districtsBrandString = CacheHelper.getCityDistricts(cityName);
		try {
			if (TextUtils.isEmpty(districtsBrandString)) {
				GetLocationListReq req = new GetLocationListReq();
				req.CityName = cityName;
				req.CityID = cityId;
				requestHttp(req, ApartmentAPI.getLocationList, StringResponse.class, true);
			} else {
				initAreaBrandInfo(districtsBrandString);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: initAreaBrandInfo 
	 * @Description: TODO(根据服务器或缓存的json串解析得到数据，并设置显示) 
	 * @param @param districtsBrandString    
	 * @return void   
	 * @throws
	 */
	private void initAreaBrandInfo(String districtsBrandString) {
		JSONObject obj = JSONObject.parseObject(districtsBrandString);
		ApartmentSearchDataInfo apartmentSearchDataInfo = ApartmentAreaUtils.createApartmentAreaDataWithBrand(obj);
		if (apartmentSearchDataInfo == null || apartmentSearchDataInfo.getChildDataInfos().size() < 1) {
			apartmentAreaView.setVisibility(View.GONE);
		} else {
			ApartmentAreaUtils.filterNullNoLeafNode(apartmentSearchDataInfo.getChildDataInfos());
			apartmentAreaView.initData(apartmentSearchDataInfo, mSSInfo, true);
		}
	}
	/**
	 * 
	 * @Title: initHistoryListView 
	 * @Description: TODO(初始化历史记录的listview) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void initHistoryListView() {
		seachHistroyListView = (ListView) findViewById(R.id.apartment_search_keyword_history_lv);
		histroyData = new ArrayList<HashMap<String, Object>>();
		histroyAdapter = new ApartmentSeachHistroyAdapter(this, histroyData, R.layout.keyword_select_item,
				new String[] { JSONConstants.ATTR_NAME }, new int[] { R.id.keyword_select_item_name });
		seachHistroyListView.addHeaderView(LayoutInflater.from(this)
				.inflate(R.layout.apartment_search_histroty_header, null));
		View footerView = LayoutInflater.from(this).inflate(R.layout.apartment_search_histroty_footer, null);
		footerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) { // 清除历史记录
				delSearchHistrotyByCityID(cityId);
				// UI刷新
				histroyAdapter.getData().clear();
				histroyAdapter.notifyDataSetChanged();
				seachHistroyListView.setVisibility(View.GONE);
			}
		});
		seachHistroyListView.addFooterView(footerView);
		seachHistroyListView.setAdapter(histroyAdapter);
		seachHistroyListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (id == -1) { // 点击的是headerView或者footerView
					view.performClick();
					return;
				}
				HashMap<String, Object> result = null;
				result = histroyData.get(position);

				if (result != null) {
					apartmentKeyword.clear();
					apartmentKeyword.setId(result.get(JSONConstants.ATTR_ID).toString());
					apartmentKeyword.setName(result.get(JSONConstants.ATTR_NAME).toString());
					apartmentKeyword.setLat(Utils.convertToDouble(result.get(JSONConstants.ATTR_LAT), 0));
					apartmentKeyword.setLng(Utils.convertToDouble(result.get(JSONConstants.ATTR_LNG), 0));
					apartmentKeyword.setType(Utils.convertToInt(result.get(JSONConstants.ATTR_TYPE),
							apartmentKeyword.TYPE_UNKNOWN));
					if (!Utils.isEmptyString(result.get(JSONConstants.ATTR_PROPERTIESID))) {
						apartmentKeyword.setId(String.valueOf(result.get(JSONConstants.ATTR_PROPERTIESID)));
					}

					m_searchEditText.setText(apartmentKeyword.getName());
					m_searchEditText.setSelection(apartmentKeyword.getName().length());

					hideDropdwonList();
					Intent intent = new Intent();
					intent.putExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT, apartmentKeyword);
					setResult(Activity.RESULT_OK, intent);
				}
				back();
			}
		});
		animationDownin = (Animation) AnimationUtils.loadAnimation(this, R.anim.activity_down_in);
	}

	/**
	 * 
	 * @Title: isKeywordClear
	 * @Description: 判断用户是否清空关键字,如果清空,则需要把上个页面的关键词也清空重置
	 * @param
	 * @return boolean
	 * @throws
	 */
	private boolean isKeywordClearByUser() {
		if (apartmentKeyword != null && !TextUtils.isEmpty(apartmentKeyword.getName())) {
			return TextUtils.isEmpty(m_searchEditText.getText().toString().trim());
		}

		return false;
	}

	/**
	 * 
	 * @Title: setEmptyKeywordForActivityResult
	 * @Description: 用户手动清空关键词的场合,需要把空关键词带回到上个页面
	 * @param
	 * @return void
	 * @throws
	 */
	private void setEmptyKeywordForActivityResult() {
		Intent data = new Intent();
		if (apartmentKeyword == null) {
			apartmentKeyword = new ApartmentKeyword();
		}
		apartmentKeyword.clear();
		data.putExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT, apartmentKeyword);

		setResult(Activity.RESULT_OK, data);
	}

	/**
	 * 
	 * @Title: initKeywordEditText 
	 * @Description: TODO(初始化搜索框) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void initKeywordEditText() {
		
		// 采用机票城市选择的输入框样式 输入框及关闭按钮都在commontitle中
		findViewById(R.id.common_head_title).setVisibility(View.GONE);
		findViewById(R.id.cityselect_keywords_normal_flight).setVisibility(View.VISIBLE);
		m_clearButton = findViewById(R.id.city_select_search_close);
		m_clearButton.setOnClickListener(this);
		m_searchEditText = ((EditText) findViewById(R.id.city_select_search));
		m_searchEditText.setHint(R.string.apartment_map_keyword_hit);
		m_searchEditText.setVisibility(View.VISIBLE);
		m_searchEditText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//		if (!StringUtils.isEmpty(apartmentKeyword.getName())) {
//			m_searchEditText.setText(apartmentKeyword.getName());
//			m_searchEditText.setSelection(apartmentKeyword.getName().length());
//			m_clearButton.setVisibility(View.VISIBLE);
//		} else {
//			m_clearButton.setVisibility(View.INVISIBLE);
//		}
		m_searchEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					showEditModeView();
				}
			}
		});
		m_searchEditText.addTextChangedListener(this);
		m_searchEditText.setOnEditorActionListener(this);
		m_cancelButton = (TextView) findViewById(R.id.city_select_search_cancel);
		m_cancelButton.setOnClickListener(this);
		// 根据传入的dismisskeywordsv关键词设定初始的显示view
		if (dismisskeywordsv) {
			showEditModeView();
		} else {
			showSelectAreaBrandView();
			// 利用额外的textview抢焦点，设置软键盘不默认弹出
			findViewById(R.id.text_notuse).requestFocus();
		}
	}

	/**
	 * 
	 * @Title: showHistroyOrSelector 
	 * @Description: TODO(根据是否有历史数据确定显示历史列表还是selector) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void showHistroyOrSelector() {
		ArrayList<HashMap<String, Object>> histroyData = getHistroyDataByCityID(cityId);
		if (histroyData == null || histroyData.size() <= 0) {
			seachHistroyListView.setVisibility(View.GONE);
		} else {
			if (seachHistroyListView.getVisibility() != View.VISIBLE) {
				seachHistroyListView.startAnimation(animationDownin);
			}
			seachHistroyListView.setVisibility(View.VISIBLE);
			histroyAdapter.setNewData(histroyData);
		}
	}

	/**
	 * 
	 * @Title: getHistroyDataByCityID 
	 * @Description: TODO(通过城市ID获取历史记录,没有返回null) 
	 * @param @param cityid
	 * @param @return    
	 * @return ArrayList<HashMap<String,Object>>   
	 * @throws
	 */
	protected ArrayList<HashMap<String, Object>> getHistroyDataByCityID(String cityid) {
		if (Utils.isEmptyString(cityid)) {
			return null;
		}
		ArrayList<HashMap<String, Object>> list = null;
		SharedPreferences channelData = this.getSharedPreferences(SP_APARTMENTSEARCHHISTROTY, Context.MODE_PRIVATE);
		String histroty = channelData.getString(cityid, null);
		if (histroty != null) {
			JSONArray suggestions = JSON.parseObject(histroty).getJSONArray(JSONConstants.ATTR_SUGGESTLIST);
			list = JSONHelper.convertArray2List(suggestions, null);
		}
		return list;
	}

	/**
	 * 
	 * @Title: saveSearchHistroty 
	 * @Description: TODO(根据城市ID,保存搜索历史) 
	 * @param @param cityid
	 * @param @param keyword    
	 * @return void   
	 * @throws
	 */
	private void saveSearchHistroty(String cityid, ApartmentKeyword keyword) {
		ApartmentSuggestListEntity entity = new ApartmentSuggestListEntity();
		entity.setLng(keyword.getLng());
		entity.setId(keyword.getId());
		entity.setName(keyword.getName());
		entity.setLat(keyword.getLat());
		entity.setPropertiesId(keyword.getId());
		entity.setAccept(keyword.isAccept());
		entity.setType(keyword.getType());

		SharedPreferences channelData = this.getSharedPreferences(SP_APARTMENTSEARCHHISTROTY, Context.MODE_PRIVATE);
		String histroty = channelData.getString(cityid, null);
		if (histroty == null) { // 还没有记录
			ArrayList<ApartmentSuggestListEntity> list = new ArrayList<ApartmentSuggestListEntity>();
			list.add(entity);

			ApartmentCitysSuggestList suggestlist = new ApartmentCitysSuggestList();
			suggestlist.setSuggestList(list);

			Editor editor = channelData.edit();
			editor.putString(cityid, JSON.toJSONString(suggestlist));
			editor.commit();
		} else { // 已有记录,更新
			ApartmentCitysSuggestList olddata = JSON.parseObject(histroty, ApartmentCitysSuggestList.class);
			if (histroty.contains(JSON.toJSONString(entity))) {// 不添加重复记录
				return;
			}
			List<ApartmentSuggestListEntity> oldListEntity = olddata.getSuggestList();
			if (oldListEntity.size() < HISTROY_MAXNUM) {
				oldListEntity.add(0, entity);
			} else {
				oldListEntity.remove(HISTROY_MAXNUM - 1);
				oldListEntity.add(0, entity);
			}
			Editor editor = channelData.edit();
			editor.putString(cityid, JSON.toJSONString(olddata));// 此处的olddata对象已经修改为新data,直接保存
			editor.commit();
		}
	}

	/**
	 * 
	 * @Title: delSearchHistrotyByCityID 
	 * @Description: TODO(通过城市ID删除历史记录) 
	 * @param @param cityid    
	 * @return void   
	 * @throws
	 */
	private void delSearchHistrotyByCityID(String cityid) {
		if (!Utils.isEmptyString(cityid)) {
			SharedPreferences channelData = this.getSharedPreferences(SP_APARTMENTSEARCHHISTROTY, Context.MODE_PRIVATE);
			Editor editor = channelData.edit();
			editor.remove(cityid);
			editor.commit();
		}
	}

	public void onClick(View v) {

		if (isWindowLocked()) {
			return;
		}

		super.onClick(v);
		int id = v.getId();
		switch (id) {
		// 清空文本框
		case R.id.city_select_search_close:
			m_searchEditText.getText().clear();
			m_searchEditText.requestFocus();
			break;
			
		// 取消键，显示AreaBrand
		case R.id.city_select_search_cancel:
			showSelectAreaBrandView();
			findViewById(R.id.text_notuse).requestFocus();
			break;
		}
	}

	@Override
	public void afterTextChanged(Editable s) {

		if (m_handler != null) {
			m_handler.removeMessages(MESSAGE_GET_SUGGESTION);
		}
		// 输入内容为空，显示历史记录
		if (s == null || s.length() == 0 || isItemSelected) {
			isItemSelected = false;
			m_clearButton.setVisibility(View.INVISIBLE);
			hideDropdwonList();
			showHistroyOrSelector();
			return;
		}

		if ("".equals(s.toString().trim())) {
			m_clearButton.setVisibility(View.INVISIBLE);
			hideDropdwonList();
			showHistroyOrSelector();
			return;
		}

		m_clearButton.setVisibility(View.VISIBLE);

		String keyword = s.toString().trim();

		// ////////////////////////Get keyword directly from server///////////

		if (m_handler != null) {
			Message msg = new Message();
			msg.what = MESSAGE_GET_SUGGESTION;
			msg.obj = keyword;
			m_handler.sendMessageDelayed(msg, KEYWORD_INPUT_INTERVAL);
		}
		// ////////////////////////Get keyword directly from server///////////
	}

	/**
	 * 
	 * @Title: getSuggestByKeyWord 
	 * @Description: (TODO向服务器发请求搜索关键词) 
	 * @param @param keyword    
	 * @return void   
	 * @throws
	 */
	private void getSuggestByKeyWord(String keyword) {
		if (!Utils.isEmptyString(cityId)) {
			HouseSuggestReq req = new HouseSuggestReq();
			req.CityId = cityId;
			req.Query = keyword;
			req.Limit = 10;
			requestHttp(req, ApartmentAPI.houseSuggest, StringResponse.class);
		}
	}

	@Override
	public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
		if (t == null) {
			return;
		}
		JSONObject result = null;
		try {
			result = (JSONObject) JSONObject.parse(((StringResponse) t).getContent());
		} catch (JSONException e) {
			LogWriter.logException(TAG, "", e);
			return;
		}
		if (ApartmentAPI.getLocationList==(ApartmentAPI) request.getRequestOption().getHusky()) {
			CacheHelper.cacheCityDistrict(this, cityName, result.toString());
			ApartmentSearchDataInfo apartmentSearchDataInfo = ApartmentAreaUtils.createHotelAreaData(result);
			if (null != apartmentSearchDataInfo) {
				ApartmentAreaUtils.filterNullNoLeafNode(apartmentSearchDataInfo.getChildDataInfos());
				apartmentAreaView.initData(apartmentSearchDataInfo, mSSInfo, true);
			}
			
		}
		if (ApartmentAPI.houseSuggest==(ApartmentAPI) request.getRequestOption().getHusky()) {
			JSONArray suggestions = ((JSONObject) result).getJSONArray(JSONConstants.ATTR_SUGGESTLIST);
			ArrayList<HashMap<String, Object>> list = JSONHelper.convertArray2List(suggestions, null);
			onSearchFinish(list);
		}
    }

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		isItemSelected = true;
		backWithResult(position);
	}

	private void onSearchFinish(final List<HashMap<String, Object>> arraylist) {

		if (this.isFinishing() || arraylist == null || arraylist.size() < 1) {
			return;
		}
		if ("".equals(m_searchEditText.getText().toString().trim())) {
			return;
		}
		// 有suggest数据就不显示历史记录视图了
		seachHistroyListView.setVisibility(View.GONE);
		
		View view = LayoutInflater.from(this).inflate(R.layout.apartment_search_dropdown_list, null);
		
		if (m_searchResultList == null) {
			m_searchResultList = (ListView) view.findViewById(R.id.search_dropdown_list);
			m_searchResultList.setOnItemClickListener(this);
		}
		SimpleAdapter adapter = new SimpleAdapter(this, arraylist, R.layout.keyword_select_item,
				new String[] { JSONConstants.ATTR_NAME }, new int[] { R.id.keyword_select_item_name }) {
			public View getView(final int position, final View convertView, final ViewGroup parent) {
				View v = super.getView(position, convertView, parent);
				v.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						TextView tv = (TextView) v.findViewById(R.id.keyword_select_item_name_type);
						keywordtypestr = tv.getText().toString();
						AdapterView<?> adapterView = (AdapterView<?>) parent;
						adapterView.performItemClick(v, position, 0);
					}
				});
				int type = Utils.convertToInt(((HashMap) super.getItem(position)).get(JSONConstants.ATTR_TYPE), 0);
				TextView tv = (TextView) v.findViewById(R.id.keyword_select_item_name_type);
				switch (type) {
				case ApartmentKeyword.TYPE_APARTMENT:
					tv.setText("房源");
					break;
				case ApartmentKeyword.TYPE_DISTRICT:
					tv.setText("行政区");
					break;
				case ApartmentKeyword.TYPE_COMMERCIAL:
					tv.setText("商圈");
					break;
				default:
					tv.setText("");
					break;
				}
				return v;
			}
		};
		m_searchResultList.setAdapter(adapter);

		m_searchResultList.setOnItemClickListener(this);
		if (m_searchResultWindow == null) {
			m_searchResultWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.MATCH_PARENT);

			m_searchResultWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

			m_searchResultWindow.setTouchInterceptor(new View.OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {

					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						m_searchResultList.onTouchEvent(event);

						m_searchResultWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);

						m_searchResultWindow.update();

					}
					return false;
				}
			});

			m_searchResultWindow.setOutsideTouchable(true);
			m_searchResultWindow.setWindowLayoutMode(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);

			m_searchResultWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
			m_searchResultWindow.showAsDropDown(m_searchEditText, DROPDOWN_OFFX, DROPDOWN_OFFY);

		}
		if (m_searchResultWindow.isShowing()) {
			m_searchResultWindow.update();
		} else{
			m_searchResultWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
			m_searchResultWindow.showAsDropDown(m_searchEditText, DROPDOWN_OFFX, DROPDOWN_OFFY);
		}
	}

	/**
	 * 
	 * @Title: hideDropdwonList 
	 * @Description: TODO(隐藏下拉框) 
	 * @param @return    
	 * @return boolean   
	 * @throws
	 */
	private boolean hideDropdwonList() {
		if (m_searchResultWindow != null && m_searchResultWindow.isShowing()) {
			m_searchResultWindow.dismiss();
			m_searchResultWindow.setFocusable(false);
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	private void backWithResult(int position) {

		HashMap<String, Object> result = null;

		if (position >= 0 && position < m_searchResultList.getAdapter().getCount()) {
			result = (HashMap<String, Object>) (m_searchResultList.getAdapter().getItem(position));
		}

		if (result != null) {
			apartmentKeyword.clear();
			apartmentKeyword.setId(result.get(JSONConstants.ATTR_ID).toString());
			apartmentKeyword.setName(result.get(JSONConstants.ATTR_NAME).toString());
			apartmentKeyword.setLat(Utils.convertToDouble(result.get(JSONConstants.ATTR_LAT), 0));
			apartmentKeyword.setLng(Utils.convertToDouble(result.get(JSONConstants.ATTR_LNG), 0));
			apartmentKeyword.setType(Utils.convertToInt(result.get(JSONConstants.ATTR_TYPE), apartmentKeyword.TYPE_UNKNOWN));
			if (!Utils.isEmptyString(result.get(JSONConstants.ATTR_PROPERTIESID))) {
				apartmentKeyword.setId(String.valueOf(result.get(JSONConstants.ATTR_PROPERTIESID)));
			}
			apartmentKeyword.setKeywordtype(keywordtypestr);
			m_searchEditText.setText(apartmentKeyword.getName());
			m_searchEditText.setSelection(apartmentKeyword.getName().length());

			hideDropdwonList();
			Intent intent = new Intent();
			intent.putExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT, apartmentKeyword);
			setResult(Activity.RESULT_OK, intent);
		}
		// 保存搜索历史
		if (!apartmentKeyword.getName().trim().equals("")) {
			if (!Utils.isEmptyString(cityId)) {
				saveSearchHistroty(cityId + "", apartmentKeyword);
			}
		}
		back();
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
			// 防止连续点击
			if (isWindowLocked()) {
				return false;
			}
			// 隐藏输入法
			InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

			Intent data = new Intent();
			apartmentKeyword.clear();
			apartmentKeyword.setName(v.getText().toString().trim());
			apartmentKeyword.setType(apartmentKeyword.TYPE_UNKNOWN);
			data.putExtra(AppConstants.BUNDLEKEY_KEYWORDOBJECT, apartmentKeyword);
			setResult(Activity.RESULT_OK, data);

			// 保存搜索历史
			if (!apartmentKeyword.getName().trim().equals("")) {
				if (!Utils.isEmptyString(cityId)) {
					saveSearchHistroty(cityId + "", apartmentKeyword);
				}
			}
			back();
		}
		return false;
	}

	public void back() {
		// 如果用户手动清空了关键词,那么需要清空上个页面已经输入的关键词数据
		if (isKeywordClearByUser()) {
			setEmptyKeywordForActivityResult();
		}

		if (m_handler != null) {
			m_handler.removeMessages(MESSAGE_LOCATE_TIMEOUT);
			m_handler.removeMessages(MESSAGE_GET_SUGGESTION);
		}
		hideDropdwonList();
		if (isFadeOut) {
			super.backFadeOut();
		} else {
			super.back();
		}
	}




	/**
	 * 
	 * @Title: showEditModeView 
	 * @Description: TODO(手动输入关键字时 展示sug,历史记录，查看附近公寓，隐藏区域信息) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void showEditModeView() {
		apartmentAreaView.setVisibility(View.GONE);
		if (!dismisskeywordsv) {
			m_cancelButton.setVisibility(View.VISIBLE);
		}
		String currenttext = m_searchEditText.getText().toString().trim();
		if (currenttext.equals("")) { // 未输入任何内容
			showHistroyOrSelector();
		} else { // 有内容
			getSuggestByKeyWord(currenttext);
		}
		Utils.showInputKeyboard(this, m_searchEditText, 50);
	}

	/**
	 * 
	 * @Title: showSelectAreaBrandView 
	 * @Description: TODO(展示区域信息，将关键词相关视图隐藏) 
	 * @param     
	 * @return void   
	 * @throws
	 */
	private void showSelectAreaBrandView() {
		hideDropdwonList();
		seachHistroyListView.setVisibility(View.GONE);
		m_cancelButton.setVisibility(View.GONE);
		if (!dismisskeywordsv ) {
			apartmentAreaView.setVisibility(View.VISIBLE);
		} else {
			apartmentAreaView.setVisibility(View.GONE);
		}
		Utils.hidenputKeyboard(this, m_searchEditText);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		hideDropdwonList();
		super.onDestroy();
	}
}
